<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div>新增取版单</div>
          </div>
        </template>
        <template #extra>
          <div>
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="取版日期" prop="takeDate">
                    <el-date-picker
                      style="width: 100%"
                      clearable
                      v-model="form.takeDate"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="取版人" prop="takeUser">
                    <el-input v-model="form.takeUser" readonly placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      readonly
                      v-model="form.createTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="机台" prop="machineName">
                    <el-input
                      v-model="form.machineName"
                      readonly
                      placeholder="请选择机台"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车间" prop="workshopName">
                    <el-input v-model="form.workshopName" readonly />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="取版明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">取版明细</span>
          </template>
          <!-- <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
          >
            选择生产单
          </el-button> -->
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesTakeversionDetailList"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="生产单编码"
              align="center"
              width="120"
              prop="produceNo"
            ></el-table-column>
            <el-table-column
              label="印刷序列号"
              min-width="120"
              prop="printProduceNo"
              align="center"
            ></el-table-column>
            <el-table-column
              label="品种"
              prop="breed"
              min-width="160"
              align="center"
            >
              <!-- <template #default="scope">
                              <dict-tag
                                  :options="ems_order_breed_type"
                                  :value="scope.row.breed"
                              />
                          </template> -->
            </el-table-column>
            <!-- <el-table-column
                          label="组成"
                          min-width="160"
                          prop="composition"
                          align="center"
                      >
                      </el-table-column> -->
            <el-table-column
              label="印张"
              width="120"
              prop="sheet"
              align="center"
            ></el-table-column>
            <el-table-column
              label="印数"
              width="120"
              prop="printAmount"
              align="center"
            ></el-table-column>
            <el-table-column
              label="贴标"
              width="120"
              prop="pieceView"
              align="center"
            ></el-table-column>
            <!-- <el-table-column label="印色" width="120" prop="printColour" align="center">
                          <template #default="scope">
                              <dict-tag
                                  :options="ems_order_print_color"
                                  :value="scope.row.printColour"
                              />
                          </template>
                      </el-table-column>
                      <el-table-column
                          label="版材数量"
                          width="120"
                          prop="sheetAmount"
                          align="center"
                      ></el-table-column>
                      <el-table-column
                          label="版材尺寸"
                          prop="sheetSize"
                          width="120"
                          align="center"
                      >
                          <template #default="scope">
                              <dict-tag
                                  :options="ems_machine_info_size"
                                  :value="scope.row.sheetSize"
                              />
                          </template>
                      </el-table-column> -->
            <el-table-column
              label="备注"
              width="200"
              align="center"
              prop="remark"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span v-if="flag">{{ scope.row.remark }}</span>
                <el-form-item v-else>
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- 领用库单明细 -->
    <orderList
      :visible="orderListOpen"
      @changeUpdate="changeOrderData"
      :orderSelectList="orderSelectList"
      :machineId="selectMachineId"
      @cancel="
        () => {
          orderListOpen = false;
        }
      "
    ></orderList>
    <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeWorkBenchData"
      :search="{ type: '2' }"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench>
  </div>
</template>

<script setup>
import SearchWorkBench from "@/components/SearchWorkBench";
import orderList from "./orderList.vue";
import {
  editTakeVersion,
  addTakeVersion,
  getTakeVersionInfo,
} from "@/api/production/takeVersion.js";
import { getTakeStay } from "@/api/production/waitTakeVersion.js";
import { getById } from "@/api/basicInfo/workbench.js";

import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  ems_machine_info_size,
  ems_order_make_up,
  ems_order_print_color,
  ems_order_breed_type,
  ems_order_make_up_fm,
} = proxy.useDict(
  "ems_order_breed_type",
  "ems_machine_info_size",
  "ems_order_make_up",
  "ems_order_print_color",
  "ems_order_make_up_fm"
);
const route = useRoute();
const router = useRouter();
const orderListOpen = ref(false);
const orderSelectList = ref([]);
const activeNames = ["1", "2"];
const userRef = ref(null);
const selectMachineId = ref("");
const flag = ref(false);
const searchVisible = ref(false);
const loading = ref(false);
const userInfo = useUserStore();
const data = reactive({
  form: {},
  mesTakeversionDetailList: [],
  rules: {
    takeUser: [
      { required: true, message: "取版人不能为空", trigger: "change" },
    ],
    takeDate: [
      {
        required: true,
        message: "取版日期不能为空",
        trigger: ["blur", "change"],
      },
    ],
    machineName: [
      { required: true, message: "机台不能为空", trigger: ["blur", "change"] },
    ],
  },
});

const { form, rules, mesTakeversionDetailList } = toRefs(data);

nextTick(() => {
  form.value.createBy = userInfo.name;
  form.value.takeUser = userInfo.name;
});

if (route.query.id) {
  getTakeStay({
    produceId: route.query.id,
    machineId: route.query.machineId,
  }).then((res) => {
    getById({ pid: route.query.machineId }).then((res) => {
      nextTick(() => {
        form.value.machineName = res.data.machineName;
        form.value.machineId = res.data.pid;
        form.value.workshopName = res.data.workshopName;
      });
    });

    res.rows.forEach((item) => {
      item.produceNo = route.query.produceNo;
      item.printProduceNo = item.producePieceNo;
      item.producePrintId = item.printId;
      delete item.createTime;
    });
    mesTakeversionDetailList.value = res.rows;
  });
}
// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选中的机台
const changeWorkBenchData = (row) => {
  mesTakeversionDetailList.value = [];
  form.value.machineName = row.machineName;
  form.value.machineId = row.pid;
  form.value.workshopName = row.workshopName;
  selectMachineId.value = row.pid;
  searchVisible.value = false;
};

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  form.value.takeDate = `${year}-${month}-${day}`;
};
getCurrentDateTime();

// 新增入库明细
const handleAddStorage = () => {
  if (!form.value.machineId) {
    return ElMessage({
      message: "请先选择机台",
      type: "warning",
    });
  }
  orderSelectList.value = mesTakeversionDetailList.value;
  orderListOpen.value = true;
};
// 选中的入库明细
const changeOrderData = (row) => {
  const codeSet = new Set(
    mesTakeversionDetailList.value.map((data) => data.pieceId)
  );
  row.forEach((item) => {
    if (!codeSet.has(item.pieceId)) {
      mesTakeversionDetailList.value.push({ ...item });
      codeSet.add(item.pieceId);
    }
  });
  orderListOpen.value = false;
};

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    mesTakeversionDetailList.value = mesTakeversionDetailList.value.filter(
      (item) =>
        item.producePrintId
          ? item.producePrintId != row.producePrintId
          : item.id != row.id
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 确认
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      addTakeVersion({
        ...form.value,
        status: 1,
        mesTakeversionDetailList: mesTakeversionDetailList.value,
      }).then((res) => {
        ElMessage({
          message: "取版成功",
          type: "success",
        });
        goBack();
      });
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
